package device

import (
	"context"
	"strings"
	"time"

	"device-admin/config/mysql"
	"device-admin/internal/define"
	"device-admin/internal/models"

	db_sharding "192.168.1.75/go-pkg/db-sharding"
	"192.168.1.75/go-pkg/errorx"
)

// SaveDeviceMetric 保存设备因子数据
func SaveDeviceMetricData(data []models.DeviceMetric) {
	dbs := db_sharding.GetDB(context.Background(), mysql.NewDB(), models.DeviceMetricTpl{}, time.Now().Unix(), time.Now().Unix())
	dbs.WriteDB.Create(&data)
}

// GetDeviceMetricNames 获取环境因子名称
func GetDeviceMetricNames(robotID string) (map[string]string, error) {
	var metricNames []string
	// 设备id不能为空
	if robotID == "" {
		return nil, errorx.New("设置id不能为空")
	}
	dbs := db_sharding.GetDB(context.Background(), mysql.NewDB(), models.DeviceMetricTpl{}, time.Now().Unix()-3600*24*30, time.Now().Unix())
	// 获取环境因子的类型
	dbs.QueryDB.
		Where("robot_id = ?", robotID).
		Group("name").
		Pluck("name", &metricNames)
	names := make(map[string]string)
	for _, metricName := range metricNames {
		names[metricName] = define.MetricName[metricName]
	}
	return names, nil
}

// GetDeviceMetricData 获取设备环境因子数据
func GetDeviceMetricData(robotID string, metricNames string, startTime int64, endTime int64) (interface{}, error) {
	var createdAtArr []int64                 // 创建时间数组
	metricData := make(map[string][]float64) // 每个环境因子的数值数组
	timelineIndex := make(map[int64]int)     // 时间序号

	// 设备id不能为空
	if robotID == "" {
		return nil, errorx.New("设备id不能为空")
	}

	// 环境因子名称不能为空
	if metricNames == "" {
		return nil, errorx.New("环境因子名称不能为空")
	}

	// 开始时间不能为空
	if startTime <= 0 {
		return nil, errorx.New("开始时间不能为空")
	}

	if endTime == 0 {
		endTime = time.Now().Unix()
	}
	dbs := db_sharding.GetDB(context.Background(), mysql.NewDB(), models.DeviceMetricTpl{}, startTime, endTime)

	// 获取时间轴
	dbs.QueryDB.
		Where("robot_id = ?", robotID).
		Where("created_at >= ? AND created_at < ?", startTime, endTime).
		Group("created_at").
		Order("created_at asc").
		Pluck("created_at", &createdAtArr)

	if len(createdAtArr) == 0 {
		return nil, nil
	}

	// 初始化创建时间序号
	for index, createdAt := range createdAtArr {
		timelineIndex[createdAt] = index
	}

	// 获取每个环境因子的值并处理
	metricNameArr := strings.Split(metricNames, ",")
	for _, metricName := range metricNameArr {
		// 获取时间段内的值，结果为数组
		var metricValue []float64
		dbs := db_sharding.GetDB(context.Background(), mysql.NewDB(), models.DeviceMetricTpl{}, startTime, endTime)
		dbs.QueryDB.
			Where("robot_id = ?", robotID).
			Where("name = ?", metricName).
			Where("created_at >= ? AND created_at <= ?", startTime, createdAtArr[len(createdAtArr)-1]).
			Order("created_at asc").
			Pluck("value", &metricValue)
		// 将查出来的值赋给相应的环境因子map
		metricData[metricName] = metricValue
	}
	// 返回结果
	return map[string]interface{}{
		"timeline": createdAtArr,
		"values":   metricData,
	}, nil
}
